<?php

namespace app\admin\controller\sales;

use app\common\controller\Backend;
use app\common\model\customer\Customer;
use app\common\model\supplier\Supplier;
use think\Db;
use think\Exception;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Cost extends Backend
{
    
    /**
     * Cost模型对象
     * @var \app\common\model\sales\Cost
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\sales\Cost;

    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $row) {
                $row->visible(['id','number','type','cost','remark','createtime','operator','company','status','source_number','is_income','sourcetime','number_obj','number_obj_id']);

            }
            $arr = array(
              1=>'收入',
              2=>'支出',
            );
            $list = collection($list)->toArray();
            $status = $this->model->coststatus();
            $types = $this->model->costtype();
            foreach ($list as &$v){
                $v['is_income'] = $arr[$v['is_income']];
                $v['type'] = $types[$v['type']];
                $v['ystatus'] = $v['status'];
                $v['status'] = $status[$v['status']];
                if($v['number_obj'] == 1){
                    $source = Customer::find($v['number_obj_id']);
                    $v['settle_name'] = $source['company'];
                }
                if($v['number_obj'] == 2){
                    $source = Supplier::find($v['number_obj_id']);
                    $v['settle_name'] = $source['nickname'];
                }
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }
    public function add(){
        if ($this->request->isAjax())
        {

            if(session('admin')['storehouse_id'] >0){
                $hrow = Db::name('storehouse')->where(array('id'=>session('admin')['storehouse_id']))->find();
            }else{
                $hrow = Db::name('storehouse')->where(array('is_default'=>1))->find();
            }
            $source_type = 0;
            $number_type = input('number_type/d',0);
            $source_number = trim(input('source_number'));
            $remark = input('remark');
            $cost = input('cost');
//            if(empty($cost) || $cost <0 || $cost == 0.00){
//                $this->error('金额异常');
//            }
            $is_income = input('is_income/d',0);
            if(empty($is_income)){
                $this->error('请选择是否支出');
            }
            switch ($number_type){
                case 1://入库单
                    $number_obj = 2;
                    $row = Db::name('purchase_enter')->where(array('number'=>$source_number))->find();
                    if(empty($row)){
                        $this->error('单据不存在');
                    }
                    $number_obj_id = $row['supplier_id'];
                    $source_type = 2;
                    break;
                case 2://出库单
                    $number_obj = 1;
                    $row = Db::name('sales_checkout')->where(array('number'=>$source_number))->find();
                    if(empty($row)){
                        $this->error('单据不存在');
                    }
                    $number_obj_id = $row['customer_id'];
                    $source_type = 7;
                    break;
                case 3://厂家直发
                    $number_obj = input('number_obj/d',0);
                    if(empty($number_obj)){
                        $this->error('未选择单据对象');
                    }
                    $row = Db::name('factory_sales')->where(array('number'=>$source_number))->find();
                    if(empty($row)){
                        $this->error('单据不存在');
                    }
                    if($number_obj == 1){
                        $number_obj_id = $row['customer_id'];
                    }else{
                        $number_obj_id = $row['supplier_id'];
                    }
                    $source_type = 12;
                    break;
                default:

                    $this->error('单据异常');
                    break;
            }
            $group = Db::name('auth_group_access')->alias('a')->where(array('uid' => session('admin')['id']))->join('zax_auth_group g', 'a.group_id = g.id')->find();
            $num = Db::name('cost')->where(array('createtime'=>array('>',strtotime(date('Y-m-d',time())))))->count();
            $data = array(
                'number'=>'FY-T-'.date('Y-m-d').'-'.getnumber($num),
                'type'=>input('type/d',1),
                'cost'=>$cost,
                'remark'=>$remark,
                'createtime'=>time(),
                'admin_id'=>session('admin')['id'],
                'group_id'=>$group['group_id'],
                'company'=>$group['name'],
                'operator'=>session('admin')['nickname'],
                'is_income'=>$is_income,
                'source_id'=>$row['id'],
                'sourcetime'=>$row['createtime'],
                'source_number'=>$source_number,
                'number_obj'=>$number_obj,
                'number_obj_id'=>$number_obj_id,
                'source_type'=>$source_type,
                'storehouse_id' => $hrow['id'],
            );
            $res = Db::name('cost')->insert($data);
            if($res){
                $this->success('添加成功');
            }
            $this->error('添加失败');
        }
        $types = $this->model->costtype();
        $this->assign('types',$types);
        return $this->view->fetch();
    }
    public function addfare(){
        if ($this->request->isAjax())
        {

            if(session('admin')['storehouse_id'] >0){
                $hrow = Db::name('storehouse')->where(array('id'=>session('admin')['storehouse_id']))->find();
            }else{
                $hrow = Db::name('storehouse')->where(array('is_default'=>1))->find();
            }
            $source_type = 0;
            $number_type = input('number_type/d',0);//来源单据类型
            $source_number = trim(input('source_number'));//来源单据编号
            $remark = input('remark');
            $admin_id = input('admin_id/d');
            $cost = input('cost');
//            if(empty($cost) || $cost <0 || $cost == 0.00){
//                $this->error('金额异常');
//            }
//            $is_income = input('is_income/d',0);
            $is_income = 2;
            if(empty($is_income)){
                $this->error('请选择是否支出');
            }
            $number_obj = 2;
            switch ($number_type){
                case 1://入库单
                    $row = Db::name('purchase_enter')->where(array('number'=>$source_number))->find();
                    if(empty($row)){
                        $this->error('单据不存在');
                    }
//                    $number_obj_id = $row['supplier_id'];
                    $source_type = 2;
                    break;
                case 2://出库单
                    $row = Db::name('sales_checkout')->where(array('number'=>$source_number))->find();
                    if(empty($row)){
                        $this->error('单据不存在');
                    }
//                    $number_obj_id = $row['customer_id'];
                    $source_type = 7;
                    break;
                case 3://厂家直发
                    $row = Db::name('factory_sales')->where(array('number'=>$source_number))->find();
                    if(empty($row)){
                        $this->error('单据不存在');
                    }
//                    if($number_obj == 1){
//                        $number_obj_id = $row['customer_id'];
//                    }else{
//                        $number_obj_id = $row['supplier_id'];
//                    }
                    $source_type = 12;
                    break;
                default:
                    $this->error('单据异常');
                    break;
            }

            $arow = Db::name('admin')->where(array('id'=>$admin_id))->find();
            $srow = Db::name('supplier')->where(array('admin_id'=>$admin_id))->find();
            if(empty($srow)){
                $source_id = Db::name('supplier')->insertGetId(array(
                        'nickname'=>$arow['nickname'],
                        'remark'=>'内部销账账号',
                    'createtime'=>time(),
                    'is_inside'=>1,
                    'admin_id'=>$admin_id,
                ));
            }else{
                $source_id = $srow['id'];
            }


            $group = Db::name('auth_group_access')->alias('a')->where(array('uid' => $admin_id))->join('zax_auth_group g', 'a.group_id = g.id')->find();

            $num = Db::name('cost')->where(array('createtime'=>array('>',strtotime(date('Y-m-d',time())))))->count();
            $data = array(
                'number'=>'FY-T-'.date('Y-m-d').'-'.getnumber($num),
                'type'=>input('type/d',1),
                'cost'=>$cost,
                'remark'=>$remark,
                'createtime'=>time(),
                'admin_id'=>$admin_id,
                'group_id'=>$group['group_id'],
                'company'=>$group['name'],
                'operator'=>$arow['nickname'],
                'is_income'=>$is_income,
                'source_id'=>$row['id'],
                'sourcetime'=>$row['createtime'],
                'source_number'=>$source_number,
                'number_obj'=>$number_obj,
                'number_obj_id'=>$source_id,
                'source_type'=>$source_type,
                'storehouse_id' => $hrow['id'],
            );
            $res = Db::name('cost')->insert($data);
            if($res){
                $this->success('添加成功');
            }
            $this->error('添加失败');
        }
        $admins = Db::name('admin')->select();
        $types = $this->model->costtype();
        $this->assign('admins',$admins);
        $this->assign('types',$types);
        return $this->view->fetch();
    }
    public function detail($ids = null){
        $row = $this->model->find($ids);
        if(empty($row)){
            $this->error('数据不存在');
        }
        if($row['source_type'] == 7){
            $name = '出库单';
            $controller = 'sales/checkout/detail';
        }
        if($row['source_type'] == 2){
            $name = '入库单';
            $controller = 'purchase/enter/detail';
        }
        if($row['source_type'] == 12){
            $name = '厂家直发';
            $controller = 'factory/sales/detail';
        }

        $types = $this->model->costtype();
        $this->assign('name',$name);
        $this->assign('controller',$controller);
        $this->assign('types',$types);
        $this->assign('row',$row);
        return $this->view->fetch();
    }
    public function printing($ids = null){
        $row = $this->model->find($ids);
        if(empty($row)){
            $this->error('数据不存在');
        }
        if($row['source_type'] == 7){
            $name = '出库单';
            $controller = 'sales/checkout/detail';
        }
        if($row['source_type'] == 2){
            $name = '入库单';
            $controller = 'purchase/enter/detail';
        }
        if($row['source_type'] == 12){
            $name = '厂家直发';
            $controller = 'factory/sales/detail';
        }
        if($row['number_obj']== 1){//客户
            $crow = Db::name('customer')->where(array('id'=>$row['number_obj_id']))->find();
            $nickname = $crow['company'];
        }else{//供应商
            $srow = Db::name('supplier')->where(array('id'=>$row['number_obj_id']))->find();
            $nickname = $srow['nickname'];
        }
        $types = $this->model->costtype();
        $this->assign('name',$name);
        $this->assign('nickname',$nickname);
        $this->assign('controller',$controller);
        $this->assign('types',$types);
        $this->assign('row',$row);
        return $this->view->fetch();
    }
    public function examine(){

        $ids = input('ids/d',0);
        $row = $this->model->find($ids);
        if(empty($row)){
            $this->error('数据不存在');
        }
        $status = input('status/d',0);
        if($status == 2){
            Db::startTrans();
            try {
                $res = Db::name('cost')->where(array('id' => $ids))->update(array('status' => $status));
                if (!$res) {
                    throw new Exception('审核失败');
                }
                switch ($row['source_type']){
                    case 2:
                        $controller = 'purchase/enter';
//                        $erow = Db::name('purchase_enter')->where(array('id'=>$row['source_id']))->find();
//                        $source = Supplier::find($row['number_obj_id']);
//                        $settle_name = $source['nickname'];
                        break;
                    case 7:
                        $controller = 'sales/checkout';
//                        $crow = Db::name('sales_checkout')->where(array('id'=>$row['source_id']))->find();
//                        $source = Customer::find($row['number_obj_id']);
//                        $settle_name = $source['company'];
                        break;
                    case 12:
                        $controller = 'factory/sales';
//                        $crow = Db::name('factory_sales')->where(array('id'=>$row['source_id']))->find();
//                        if($row['number_obj'] == 1){
//                            $source = Customer::find($row['number_obj_id']);
//                            $settle_name = $source['company'];
//                        }
//                        if($row['number_obj'] == 2){
//                            $source = Supplier::find($row['number_obj_id']);
//                            $settle_name = $source['nickname'];
//                        }
                        break;
                    default:
                        throw new Exception('暂不支持');
                        break;
                }
                if($row['number_obj'] == 1){
                    $source = Customer::find($row['number_obj_id']);
                    $settle_name = $source['company'];
                }
                if($row['number_obj'] == 2){
                    $source = Supplier::find($row['number_obj_id']);
                    $settle_name = $source['nickname'];
                }

                $ress = Db::name('analysis')->insert(array(
                    'is_income'=>$row['is_income'],
                    'source'=>16,
                    'cost'=>$row['cost'],
                    'admin_id'=>$row['admin_id'],
                    'group_id'=>$row['group_id'],
                    'company'=>$row['company'],
                    'operator'=>$row['operator'],
                    'source_id' => $row['source_id'],
                    'obj_id' => $source['id'],
                    'controller'=>$controller,
                    'settle_name'=>$settle_name,
                    'number'=>$row['number'],
                    'createtime'=>time(),
                    'storehouse_id' => $row['storehouse_id'],
                    'explain'=>$row['remark'],//摘要
                ));
                if (!$ress) {
                    throw new Exception('数据异常');
                }
                Db::name('examine_log')->insert(array(
                    'admin_id'=>session('admin')['id'],
                    'type'=>1,
                    'createtime'=>time(),
                    'controller'=>'sales/cost',
                    'source_id'=>$ids,
                    'source'=>16,
                    'remark'=>'费用单',
                    'number'=>isset($row['number'])?$row['number']:'',
                ));
                Db::commit();
                return array(
                    'code' => 1,
                    'msg' => '成功'
                );
            }catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error($e->getMessage());
            }
        }elseif ($status == 3){
            $res = Db::name('cost')->where(array('id'=>$ids))->update(array('status'=>$status));
            if($res){
                Db::name('examine_log')->insert(array(
                    'admin_id'=>session('admin')['id'],
                    'type'=>2,
                    'createtime'=>time(),
                    'controller'=>'sales/cost',
                    'source_id'=>$ids,
                    'source'=>16,
                    'remark'=>'费用单',
                    'number'=>isset($row['number'])?$row['number']:'',
                ));
                $this->success('审核成功');
            }
            $this->error('审核失败');
        }else{
            $this->error('状态异常');
        }
    }
    public function cancelbill($ids = null){
        $row = $this->model->find($ids);
        if(!$row){
            $this->error('非法操作');
        }
        $reason = input('reason');
        if(empty($reason)){
            $this->error('理由必须填写');
        }
        if($row['status'] != 2){
            $this->error('状态异常');
        }
        $analysis = Db::name('analysis')->where(array(
            'source'=>16,
            'source_id' => $row['source_id'],
            'storehouse_id' => $row['storehouse_id'],
        ))->find();

        //只有财务数据在待处理的时候 才能处理
        if($analysis['status'] != 1){
            $this->error('财务状态异常,请处理');
        }

        Db::startTrans();
        try {

            $this->model->save(array('status'=>4),array('id'=>$ids));

            $group = Db::name('auth_group_access')->alias('a')->where(array('uid' => session('admin')['id']))->join('zax_auth_group g', 'a.group_id = g.id')->find();


            Db::name('cancel_bill')
                ->insert(array(
                    'reason' => $reason,
                    'source' => 16,
                    'admin_id' => session('admin')['id'],
                    'group_id' => $group['group_id'],
                    'company' => $group['name'],
                    'operator' => session('admin')['nickname'],
                    'controller' => 'sales/cost',
                    'source_id' => $row['id'],
                    'number' => isset($row['number'])?$row['number']:'',
                    'createtime' => time(),
                ));

            Db::name('examine_log')->insert(array(
                'admin_id'=>session('admin')['id'],
                'type'=>3,
                'createtime'=>time(),
                'controller'=>'sales/cost',
                'source_id'=>$ids,
                'source'=>16,
                'remark'=>'费用单',
                'number'=>isset($row['number'])?$row['number']:'',
            ));

            //财务单据作废
            $ress = Db::name('analysis')->where(array(
                'id' => $analysis['id']
            ))->update(array('status' => 4));
            if (!$ress) {
                throw new Exception('数据异常');
            }


            Db::commit();
            return array(
                'code' => 1,
                'msg' => '成功'
            );
        }catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error($e->getMessage());
        }

    }


}
